create procedure wp_GetParents
	@currentState int,
	@parentState int
as
	set nocount on

	declare @dbid int
	declare @state int
	declare @infostate int
	declare @sourcestate int
	declare @branchid int
	declare @cursorinfostate int
	declare @cursorbranchid int
	declare @table table(States int)
	declare @states table(States int, Branch int)

	select @infostate = max(State) from Info where State <= @currentState
	select @branchid = BranchID from Info where State = @infostate
	select @sourcestate = SourceState from Branch where ID = @branchid

	select @dbid = o.DBID from Objects o
		inner join Data d on d.ObjectID = o.ID 
		where d.State = @parentState

	if isnull(@branchid, 0) = 0
		select @sourcestate = 0

	insert into @states(States)
		select State from Data d
			inner join Objects o on o.ID = d.ObjectID
			where o.DBID = @dbid
				and State >= @parentState
				and State <= @currentState
		order by State desc

	update @states
		set Branch = coalesce(@branchid, 0)
		where States > @sourcestate
			and Branch is null


	while @sourcestate >= @parentState
	begin
		select @infostate = max(State) from Info where State <= @sourcestate
		select @branchid = BranchID from Info where State = @infostate

		if isnull(@branchid, 0) = 0
			select @sourcestate = 0
		else
			select @sourcestate = SourceState from Branch where ID = @branchid

		update @states
			set Branch = coalesce(@branchid, 0)
			where States > @sourcestate
				and Branch is null

	end

	declare c cursor for
		select State from Data d
			inner join Objects o on o.ID = d.ObjectID
			where o.DBID = @dbid
				and State >= @parentState
				and State <= @currentState
		order by State desc

	open c

	fetch next from c into @state
	while @@fetch_status = 0
	begin
		select @cursorinfostate = max(State) from Info where State <= @state
		select @cursorbranchid = BranchID from Info where State = @cursorinfostate

		if coalesce(@cursorbranchid, 0) = (select Branch from @states where States = @state)
			insert into @table
				select @state

		fetch next from c into @state
	end

	close c
	deallocate c

	set nocount off

	select States from @table